package main

/*
cd src/io/tcp
go run tcp_server.go
*/
import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io"
	"log"
	"net"
	"os"
)

func main() {
	// 加载服务器证书和私钥
	cert, err := tls.LoadX509KeyPair("tls/server.crt.pem", "tls/server.key.pem")
	//cert, err := tls.LoadX509KeyPair("server.crt", "server.key")
	if err != nil {
		log.Fatalf("加载证书和私钥失败: %v", err)
	}

	// 加载根证书
	caCert, err := os.ReadFile("tls/ca.crt.pem")
	if err != nil {
		log.Fatalf("读取根证书失败: %v", err)
	}
	caCertPool := x509.NewCertPool()
	caCertPool.AppendCertsFromPEM(caCert)

	// 配置TLS
	config := &tls.Config{
		Certificates: []tls.Certificate{cert},
		ClientCAs:    caCertPool,
		ClientAuth:   tls.RequireAndVerifyClientCert,
	}

	// 监听TCP端口
	listener, err := tls.Listen("tcp", ":8443", config)
	if err != nil {
		log.Fatalf("监听失败: %v", err)
	}
	defer listener.Close()

	fmt.Println("服务器正在监听 :8443...")

	for {
		// 接受客户端连接
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("接受连接时出错: %v", err)
			continue
		}
		go handleConnection(conn)
	}
}

func handleConnection(conn net.Conn) {
	defer conn.Close()

	// 从客户端读取数据
	buffer := make([]byte, 1024)
	n, err := conn.Read(buffer)
	if err != nil {
		if err != io.EOF {
			log.Printf("读取数据时出错: %v", err)
		}
		return
	}

	// 处理接收到的数据
	message := string(buffer[:n])
	fmt.Printf("收到客户端消息: %s\n", message)

	// 向客户端发送响应
	response := "已收到消息: " + message
	_, err = conn.Write([]byte(response))
	if err != nil {
		log.Printf("发送响应时出错: %v", err)
	}
}
